05. Flask Part II

Flask Part II

Flask Part II

Now that we're ready to make non-simple requests, we'll learn about and practice making complex GET requests and additional requests (POST, PATCH, and DELETE), using CORS and basic error handling.

FSND C2 L3 A07 Flask Part 2 Intro

Flask Route Decorator

Flask Route Decorator

You've already seen the @app.route decorator used in its most basic form like so:

@app.route('/hello')
def get_greeting():
    return jsonify({'message':'Hello, World!'})

In addition, the @app.route decorator can handle Variable Rules and multiple HTTP methods

Variable Rules

In our endpoint naming scheme we follow collection/item/collection . In order to handle that variable item. In order to handle that variability in Flask, you add a <variable_name> within the path argument of the @app.route decorator, which is then passed to the function as a keyword argument variable_name.

You can also specify the type of the argument by using <converter:variable_name> syntax.

@app.route('/entrees/<int:entree_id>')
def retrieve_entree(entree_id):
    return 'Entree %d' % entree_id

HTTP Methods

By default, the @app.route decorator answers only get requests. In order to enable more requests types, pass the method parameter to the decorate including a list of string methods.

@app.route('/hello', methods=['GET', 'POST'])
def greeting():
    if request.method == 'POST':
        return create_greeting()
    else:
        return send_greeting()

OPTIONS requests are automatically implemented and HEAD is also automatically implemented if GET is present.

FSND C2 L3 A08 Flask Pagination Example Part 1

Flask Pagination Summary

Pagination in Flask

When handling large collections of data, attempting to serialize and send all of that data to the frontend will slow down the response and rendering to the client.

A common way to handle this issue is to paginate the data you're sending, and send it in chunks instead. Similar to variables discussed above, flask can handle request arguments to get additional request conditions such as page or search terms.

Query Parameters

The below examples show the format of query parameters. When writing query parameters convention dictates that:

  • A question mark precedes the query parameters
  • Parameters are in key=value pairs with an equal sign in between the key and value
  • Sets of parameters are separated by an ampersand
www.example.com/entrees?page=1

www.example.com/entrees?page=1&allergens=peanut

Request Arguments

In flask, when a request is received with query params the route in the @app.route decorator remains the same and the request object arguments contains the parameter. You access it as shown below. request.args is a Python dictionary so we use the get method to access the value and provide a default value, in this case 1.

@app.route('/entrees', methods=['GET'])
  def get_entrees():
    page = request.args.get('page', 1, type=int)

Flask Part II Quiz

What is missing from the following code?

@app.route('/books/<int:book_id>')
def retrieve_book():
    return 'Book %d' % book_id
SOLUTION: Function argument `book_id`

Flask Part II Quiz 2

Choose all correct ways to write an @app.route decorator for get requests in flask

SOLUTION:
  • @app.route('/')
  • @app.route('/quiz', methods=['GET', ‘POST’])

QUIZ QUESTION: :

Match the sample app.route decorators with the concepts they demonstrate.

ANSWER CHOICES:



Sample Decorator

Concept

Method Specification

Variable Rules

Basic app.route

SOLUTION:

Sample Decorator

Concept

Method Specification

Variable Rules

Basic app.route

Which of the following paths including query params are formatted correctly?

SOLUTION:
  • www.sample.com/students/3/notes?page=2
  • www.sample.com/students?page=2&age=12

For the following app.route, which of the following lines are correct ways to get the query parameter values?

@app.route('/students', methods=['GET'])
def get_students():
  # your code here
SOLUTION:
  • page = request.args.get('page', 1, type=int)
  • age = request.args.get('age', 1, type=int)

QUESTION:

Write a basic app.route decorator that DOES NOT use variable rules or method specification.

SOLUTION:

NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer

QUESTION:

Write an app.route decorator that uses ONLY method specification, NOT variable rules.

SOLUTION:

NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer

QUESTION:

Write an app.route decorator that uses ONLY variable rules, NOT method specification.

SOLUTION:

NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer

QUESTION:

Write a path that starts with www.example.com and includes two query parameters of your choice.

SOLUTION:

NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer

FSND C2 L3 A09 Flask Pagination Example Part 2

FSND C2 L3 A10 Flask Pagination Summary

Workspace

This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity , so you may be able to download them there.

Workspace Information:

  • Default file path:
  • Workspace type: jupyter-lab
  • Opened files (when workspace is loaded): n/a